package function.search;

import java.io.IOException;

import boot.Boot;
import db.DBListener;
import db.DBReader;
import db.Mp3DBRecord;
import files.Files;
import function.ChainMp3;
import function.ChainMp3Impl;

public class DBSearchFunction2 implements SearchFunction, DBListener {

	private DBReader dbReader;
	private ChainMp3 searchResult;
	private String searchEntry;
	private String dbFile;

	public DBSearchFunction2(String aDbFile) {
		super();
		dbFile = aDbFile;
	}

	public ChainMp3 find(String aSearchEntry) throws Throwable {
		searchEntry = aSearchEntry.toLowerCase();
		searchResult = null;
		dbReader = new DBReader(Files.BOOT_ROOT + "/" + dbFile);
		dbReader.addListener(this);
		dbReader.readDB();
		return searchResult;
	}

	public void processRecord(Mp3DBRecord record) {
		int numChar = 2;
		String title = record.getTitle();
		if (title.length() < numChar) {
			for (int i = 0; i < numChar - title.length(); i++) {
				title += " ";
			}
		}
		String recordKey = title.substring(0, numChar).toLowerCase();
		if (searchEntry.equals(recordKey)) {
			if (searchResult == null) {
				searchResult = new ChainMp3Impl(record.getMp3File(), null, null);
			} else {
				searchResult.setLast(record.getMp3File());
			}
		} else if (recordKey.compareTo(searchEntry) > 0) {
			try {
				dbReader.stopReading();
			} catch (IOException e) {
				Boot.alertException(e, this, "processRecord()");
			}
		}
	}

	public void readingDone() {
	}
}
